package com.framework.buss.bridge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.framework.buss.bridge.model.WordTree;
import com.framework.buss.bridge.mapper.WordTreeMapper;
import com.framework.buss.bridge.service.IWordTreeService;
import com.framework.buss.bridge.vo.WordTreeSelectedVO;
import com.framework.common.exception.BusinessException;
import com.framework.common.model.SelectTreeModel;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 模板word目录表
 * @Author: jeecg-boot
 * @Date:   2023-08-14
 * @Version: V1.0
 */
@Log4j2
@Service
public class WordTreeServiceImpl extends ServiceImpl<WordTreeMapper, WordTree> implements IWordTreeService {
	@Override
	public void addWordTree(WordTree wordTree) {
	   //新增时设置hasChild为0
	    wordTree.setHasChild(IWordTreeService.NOCHILD);
		if(ObjectUtils.isEmpty(wordTree.getPid())){
			wordTree.setPid(IWordTreeService.ROOT_PID_VALUE);
		}else{
			//如果当前节点父ID不为空 则设置父节点的hasChildren 为1
			WordTree parent = baseMapper.selectById(wordTree.getPid());
			if(parent!=null && !"1".equals(parent.getHasChild())){
				parent.setHasChild(IWordTreeService.HASCHILD);
				baseMapper.updateById(parent);
			}
		}
		baseMapper.insert(wordTree);
	}
	
	@Override
	public void updateWordTree(WordTree wordTree) {
		WordTree entity = this.getById(wordTree.getId());
		if(entity==null) {
			throw new BusinessException("未找到对应实体");
		}
		String old_pid = entity.getPid();
		String new_pid = wordTree.getPid();
		if(!old_pid.equals(new_pid)) {
			updateOldParentNode(old_pid);
			if(ObjectUtils.isEmpty(new_pid)){
				wordTree.setPid(IWordTreeService.ROOT_PID_VALUE);
			}
			if(!IWordTreeService.ROOT_PID_VALUE.equals(wordTree.getPid())) {
				baseMapper.updateTreeNodeStatus(wordTree.getPid(), IWordTreeService.HASCHILD);
			}
		}
		baseMapper.updateById(wordTree);
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteWordTree(String id)  {
		//查询选中节点下所有子节点一并删除
        id = this.queryTreeChildIds(id);
        if(id.indexOf(",")>0) {
            StringBuffer sb = new StringBuffer();
            String[] idArr = id.split(",");
            for (String idVal : idArr) {
                if(idVal != null){
                    WordTree wordTree = this.getById(idVal);
                    String pidVal = wordTree.getPid();
                    //查询此节点上一级是否还有其他子节点
                    List<WordTree> dataList = baseMapper.selectList(new QueryWrapper<WordTree>().eq("pid", pidVal).notIn("id",Arrays.asList(idArr)));
                    boolean flag = (dataList == null || dataList.size() == 0) && !Arrays.asList(idArr).contains(pidVal) && !sb.toString().contains(pidVal);
                    if(flag){
                        //如果当前节点原本有子节点 现在木有了，更新状态
                        sb.append(pidVal).append(",");
                    }
                }
            }
            //批量删除节点
            baseMapper.deleteBatchIds(Arrays.asList(idArr));
            //修改已无子节点的标识
            String[] pidArr = sb.toString().split(",");
            for(String pid : pidArr){
                this.updateOldParentNode(pid);
            }
        }else{
            WordTree wordTree = this.getById(id);
            if(wordTree==null) {
                throw new BusinessException("未找到对应实体");
            }
            updateOldParentNode(wordTree.getPid());
            baseMapper.deleteById(id);
        }
	}
	
	@Override
    public List<WordTree> queryTreeListNoPage(LambdaQueryWrapper<WordTree> queryWrapper) {
        List<WordTree> dataList = baseMapper.selectList(queryWrapper);
        List<WordTree> mapList = new ArrayList<>();
        for(WordTree data : dataList){
            String pidVal = data.getPid();
            //递归查询子节点的根节点
            if(pidVal != null && !IWordTreeService.NOCHILD.equals(pidVal)){
                WordTree rootVal = this.getTreeRoot(pidVal);
                if(rootVal != null && !mapList.contains(rootVal)){
                    mapList.add(rootVal);
                }
            }else{
                if(!mapList.contains(data)){
                    mapList.add(data);
                }
            }
        }
        return mapList;
    }

    @Override
    public List<SelectTreeModel> queryListByCode(String parentCode) {
        String pid = ROOT_PID_VALUE;
        if (!ObjectUtils.isEmpty(parentCode)) {
            LambdaQueryWrapper<WordTree> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WordTree::getPid, parentCode);
            List<WordTree> list = baseMapper.selectList(queryWrapper);
            if (list == null || list.size() == 0) {
                throw new BusinessException("该编码【" + parentCode + "】不存在，请核实!");
            }
            if (list.size() > 1) {
                throw new BusinessException("该编码【" + parentCode + "】存在多个，请核实!");
            }
            pid = list.get(0).getId();
        }
        return baseMapper.queryListByPid(pid, null);
    }

    @Override
    public List<SelectTreeModel> queryListByPid(String pid) {
        if (ObjectUtils.isEmpty(pid)) {
            pid = ROOT_PID_VALUE;
        }
        return baseMapper.queryListByPid(pid, null);
    }

    @Override
    public List<WordTreeSelectedVO> listAll(WordTreeSelectedVO vo) {
        List<WordTreeSelectedVO> list = baseMapper.findSelected(vo);
        List<WordTreeSelectedVO> tree = getChildren(list, "0");
        return tree;
    }

    @Override
    public List<WordTree> findByIds(List<String> idList) {
        return baseMapper.selectBatchIds(idList);
    }

    @Override
    public WordTree findById(String originId) {
        return baseMapper.selectById(originId);
    }

    private List<WordTreeSelectedVO> getChildren(List<WordTreeSelectedVO> allList, String pid) {
        List<WordTreeSelectedVO> tree = allList.stream()
                .filter(it-> {
                    if (null == it.getPid()) {
                        it.setPid(StringUtils.EMPTY);
                    }
                    return it.getPid().equals(pid);
                }).sorted(Comparator.comparingInt(WordTreeSelectedVO::getSort))
                .collect(Collectors.toList());

        tree.forEach(it -> it.setChildren(getChildren(allList, it.getId())));
        return tree;
    }

    /**
	 * 根据所传pid查询旧的父级节点的子节点并修改相应状态值
	 * @param pid
	 */
	private void updateOldParentNode(String pid) {
		if(!IWordTreeService.ROOT_PID_VALUE.equals(pid)) {
			Long count = baseMapper.selectCount(new QueryWrapper<WordTree>().eq("pid", pid));
			if(count==null || count<=1) {
				baseMapper.updateTreeNodeStatus(pid, IWordTreeService.NOCHILD);
			}
		}
	}

	/**
     * 递归查询节点的根节点
     * @param pidVal
     * @return
     */
    private WordTree getTreeRoot(String pidVal){
        WordTree data =  baseMapper.selectById(pidVal);
        if(data != null && !IWordTreeService.ROOT_PID_VALUE.equals(data.getPid())){
            return this.getTreeRoot(data.getPid());
        }else{
            return data;
        }
    }

    /**
     * 根据id查询所有子节点id
     * @param ids
     * @return
     */
    private String queryTreeChildIds(String ids) {
        //获取id数组
        String[] idArr = ids.split(",");
        StringBuffer sb = new StringBuffer();
        for (String pidVal : idArr) {
            if(pidVal != null){
                if(!sb.toString().contains(pidVal)){
                    if(sb.toString().length() > 0){
                        sb.append(",");
                    }
                    sb.append(pidVal);
                    this.getTreeChildIds(pidVal,sb);
                }
            }
        }
        return sb.toString();
    }

    /**
     * 递归查询所有子节点
     * @param pidVal
     * @param sb
     * @return
     */
    private StringBuffer getTreeChildIds(String pidVal,StringBuffer sb){
        List<WordTree> dataList = baseMapper.selectList(new QueryWrapper<WordTree>().eq("pid", pidVal));
        if(dataList != null && dataList.size()>0){
            for(WordTree tree : dataList) {
                if(!sb.toString().contains(tree.getId())){
                    sb.append(",").append(tree.getId());
                }
                this.getTreeChildIds(tree.getId(),sb);
            }
        }
        return sb;
    }

}
